package cn.darkfire.CarWeb.Controller;

import cn.darkfire.CarWeb.POJO.Car;
import cn.darkfire.CarWeb.Service.CarService;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/car/show.do")
public class GetCarsController extends HttpServlet {

    @Autowired
    private CarService carService;

    //在spring中注入可能会失败,重写init方法让spring重新获取注入窗口即可
    @Override
    public void init() throws ServletException {
        super.init();
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,this.getServletContext());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Car> cars = carService.getAllCar();
        JSONObject obj = new JSONObject();
        JSONObject data = new JSONObject();
        try {
            obj.putOpt("data",data);
            obj.put("count",cars.size());
            JSONObject car = null;
            for(int i = 0;i<cars.size();i++){
                car = new JSONObject();
                car.put("id",cars.get(i).getCarID());
                car.put("name",new StringBuilder(cars.get(i).getCarName()));
                car.put("type",cars.get(i).getCarType());
                car.put("price",cars.get(i).getCarPrice());
                data.putOpt(String.valueOf(i),car);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        resp.setHeader("Content-Type","application/json;charset=utf-8");
        resp.getWriter().print(obj.toString());
    }

    //测试类
    @Test
    public void select(){
        //这点实现的仅仅是 CarDao carDao = new CarDao(); 降低耦合性
        //ApplicationContext ap = new FileSystemXmlApplicationContext("src/applicationContext.xml");
        //CarDao dao = ap.getBean("carDao",CarDao.class); //通过注解来获取实例 CarService car = new CarService();
////        dao.insert(new Car("11","1","1","1"));
//        System.out.println(dao.searchCar("1").get(0).toString());
//        Car car = new Car();
//        car.setCarID("21");
//        car.setCarName("1");
//        car.setCarType("1");
//        car.setCarPrice("2");
//        if (dao.insert(car) == 1){
//            System.out.println("it's ok！");
//        }
        //carService = ap.getBean("carService", CarServiceImpl.class);
        carService.getAllCar();
    }

}
